package org.testile;

/**
 *
 * @author hvizmar
 */
public class InstantiationUtils {

	public static <T> T getInstance(Class<T> expectedType, String className) {
		Class<?> type = getClass(className);
		if (expectedType.isAssignableFrom(type)) {
			return expectedType.cast(instantiateClass(type));
		}

		throw new IllegalArgumentException("Instances of class [" + className + "] are not subtypes of [" + expectedType + "]");
	}

	public static Class<?> getClass(String className) {
		try {
			return Class.forName(className);
		} catch (ClassNotFoundException ex) {
			throw new IllegalArgumentException("Cannot load class [" + className + "]", ex);
		}
	}

	public static <T> T instantiateClass(Class<T> type) {
		try {
			return type.newInstance();
		} catch (InstantiationException ex) {
			throw new IllegalArgumentException("Could not create an instance of type [" + type + "]", ex);
		} catch (IllegalAccessException ex) {
			throw new IllegalArgumentException("Could not create an instance of type [" + type + "]", ex);
		}
	}
}
